package com.bearlair.ch1;

import com.bearlair.utils.Tools;

/**
 * 比较两个方法的不同
 */
public class Starter {

    public static void main(String[] args) {
        Thread t;
        CountingTask ct = new CountingTask();
        final int numberOfProcessors = Runtime.getRuntime().availableProcessors();
        System.out.println(numberOfProcessors);
        for (int i = 0; i < 2 * numberOfProcessors; i++) {
            t = new Thread(ct);
            t.start();
        }

        for (int i = 0; i < 2 * numberOfProcessors; i++) {
            t = new CountingThread();
            t.start();
        }

    }

    static class CountingTask implements Runnable {
        private final Counter counter = new Counter();
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                doSomething();
                counter.increment();
            }
            System.out.println("CountingTask:" + counter.value());
        }

        private void doSomething(){
            Tools.randomPause(80);
        }
    }

    static class CountingThread extends Thread{
        private final Counter counter = new Counter();
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                doSomething();
                counter.increment();
            }
            System.out.println("CountingThread:" + counter.value());
        }

        private void doSomething(){
            Tools.randomPause(80);
        }
    }

    static class Counter {
        private int count = 0;

        public synchronized void increment() {
            count++;
        }

        public int value() {
            return count;
        }
    }
}
